package com.yiranLTD.controller;

import com.yiranLDT.Result;
import com.yiranLDT.User;
import com.yiranLTD.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    public static final int SALT_LENGTH=16;
    public static final String HASH_ALGORITHM = "SHA-256";

    /**
     * 用户注册接口
     * @param username
     * @param password
     * @throws NoSuchAlgorithmException
     */
    @GetMapping("/user/register/{username}/{password}")
    public Result register(@PathVariable String username, @PathVariable String password) throws NoSuchAlgorithmException {

        //这里其实还是应该写到服务层去的 ，下次注意！！！！！！
        //生成盐
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[SALT_LENGTH];
        random.nextBytes(salt);
        String s = Base64.getEncoder().encodeToString(salt);
        String passwordAndSalt=password+s;

        MessageDigest instance = MessageDigest.getInstance(HASH_ALGORITHM);
        byte[] digest = instance.digest(passwordAndSalt.getBytes(StandardCharsets.UTF_8));
        passwordAndSalt=Base64.getEncoder().encodeToString(digest);

        //构造用户数据
        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordAndSalt);
        user.setSalt(s);

        boolean save = userService.save(user);
        if(save){
            log.info("用户注册成功");
            return Result.success();
        }
        return Result.error("注册失败");
    }


    @GetMapping("/user/login/{username}/{password}")
    public Result<User> login(@PathVariable String username,@PathVariable String password){
        return userService.login(username,password);
    }
}
